package nacos

import (
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/pkg/errors"
	"sync"
)

var (
	namingClient naming_client.INamingClient
	onceNacos    sync.Once
)

func InitNacos() (naming_client.INamingClient, error) {
	onceNacos.Do(func() {
		// 创建 Nacos 客户端配置
		clientConfig := constant.ClientConfig{
			NamespaceId: "public",
		}

		serverConfigs := []constant.ServerConfig{
			*constant.NewServerConfig(
				"192.168.109.133",
				18848,
				constant.WithScheme("http"),
				constant.WithContextPath("/nacos"),
			),
		}

		namingClient, _ = clients.NewNamingClient(
			vo.NacosClientParam{
				ClientConfig:  &clientConfig,
				ServerConfigs: serverConfigs,
			},
		)

	})

	if namingClient == nil {
		return nil, errors.New("mysql failed to get store")
	}
	return namingClient, nil
}

func Register(serviceName string, ip string, port uint64) (bool, error) {
	return namingClient.RegisterInstance(vo.RegisterInstanceParam{
		Ip:          ip,
		Port:        port,
		ServiceName: serviceName,
		Weight:      10,
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
	})
}
